package com.zjl.cms.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.zjl.cms.base.model.BadgesCount;
import com.zjl.cms.base.model.Const;
import com.zjl.cms.dao.BaseDao;
import com.zjl.cms.model.AuthMenu;
import com.zjl.cms.model.Notify;
import com.zjl.cms.model.User;
import com.zjl.cms.model.UserRole;


@Service
public class UserService{
	
	@Autowired
	private BaseDao baseDao;
	
	
//	public List validationUser(User user) {
//		List re=baseDao.select("com.zjl.cms.dao.UserMapper.validationUser",user);
//		return re;
//	}
	
	public User selectByUserName(String userName) {
		List re=baseDao.select("com.zjl.cms.dao.UserMapper.selectByUsername",userName);
		User reUser=null;
		if(re!=null&&re.size()==1){
			reUser=(User) re.get(0);
		}
		return reUser;
	}
	
	public List<AuthMenu> getMenuList(String id) {
		List<AuthMenu> menus = new ArrayList<AuthMenu>();
		User user = (User) baseDao.selectOne("com.zjl.cms.dao.UserMapper.selectByPrimaryKey", id);
		List<UserRole> roles = baseDao.select("com.zjl.cms.dao.UserRoleMapper.selectByUserid", id);
		for(UserRole role : roles){
			List<AuthMenu> menusList = baseDao.select("com.zjl.cms.dao.AuthMenuMapper.selectByRoleid",role.getRoleId());
			for(AuthMenu menu : menusList){
				if(!menus.contains(menu)){
					menus.add(menu);
				}
			}
		}
		return menus;
	}

	public User login(String username, String md5Password) {
		System.out.println("用户名密码"+username+"   md5密码"+md5Password);
		User user=selectByUserName(username);
		Notify n=new Notify();
		BadgesCount b=new BadgesCount();
		if (user != null&&user.getPassword().equals(md5Password)) {
			user.setAuthMenus(getMenuList(user.getId()));
			//获取未读消息的数量
			n.setOwnId(user.getId());
			n.setStatus(Const.NOTIFY_UNREAD);
			b.setNotifies(Integer.valueOf(baseDao.selectOne("com.zjl.cms.dao.NotifyMapper.selectCount", n).toString()));
			user.setBadgesCount(b);
		}
		return user;
	}

}
